<?php
class LoginzaModel extends CModel {
 
    public $identity;
    public $provider;
    public $email;
    public $full_name;
    public $token;
    public $error_type;
    public $error_message;
 
    private $loginzaAuthUrl = 'http://loginza.ru/api/authinfo?token=';
 
    public function rules() {
        return array(
            array('identity,provider,token', 'required'),
            array('email', 'email'),
            array('identity,provider,email', 'length', 'max'=>255),
            array('full_name', 'length', 'max'=>55),
        );
    }
 
    public function attributeLabels() {
        return array(
            'identity'=>'Идентификатор сервиса аутентификации',
            'provider'=>'Сервис аутентификации',
            'email'=>'eMail',
            'full_name'=>'Имя',
        );
    }
 
    public function getAuthData() {
        $authData = json_decode(file_get_contents($this->loginzaAuthUrl.$this->token),true);
        $this->setAttributes($authData);
        
        if(isset($authData['name'])) {
            if(strstr($authData['identity'], 'twitter')) {
                $this->full_name = 'twitter'.$authData['uid'];
            }
            else if(strstr($authData['identity'], 'facebook')) {
                $this->full_name = $authData['email'];
            }
            else if(strstr($authData['identity'], 'vkontakte')) {
                $this->full_name = $authData['email'];
            }
        }
    }

    public function login() {
        $identity = new LoginzaUserIdentity();
        if ($identity->authenticate($this)) {
            Yii::app()->user->login($identity,3600*24*7);
            return true;
        }
        return false;
    }
 
    public function attributeNames() {
        return array(
            'identity',
            'provider',
            'email',
            'full_name',
            'token',
            'error_type',
            'error_message'
        );
    }
}

//
//stdClass Object
//(
//    [identity] => http://twitter.com/vasili
//    [provider] => http://twitter.com/
//    [nickname] => vasili
//    [web] => stdClass Object
//        (
//            [default] => http://vasili.com
//        )
// 
//    [name] => stdClass Object
//        (
//            [full_name] => vasili
//        )
// 
//    [photo] => http://a2.twimg.com/profile_images/654897/a_772341f_normal.jpg
//    [uid] => 56465789
//)
